package com.example.kiratest.realize;

import okhttp3.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GooglePlayScraper {
    private static final String PLAY_STORE_URL = "https://play.google.com/store/apps/details";
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(20, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .addInterceptor(chain -> {
                // 基础请求头
                Request request = chain.request().newBuilder()
                        .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36 Edg/123.0.0.0")
                        .header("Accept-Language", "en-US,en;q=0.9")
                        .header("Accept-Encoding", "gzip, deflate")
                        .header("Referer", "https://play.google.com/")
                        .header("DNT", "1")
                        .header("Upgrade-Insecure-Requests", "1")
                        .build();

                // 随机延迟
                try {
                    Thread.sleep(2000 + (long)(Math.random() * 2000));
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }

                return chain.proceed(request);
            })
            .build();

    public static String getAppVersion(String packageName) {
        try {
            System.out.println("Fetching version for: " + packageName);

            // 第一次尝试
            String version = tryGetVersion(packageName, "en", "us");
            if (version != null) return version;

            // 第二次尝试
            System.out.println("First attempt failed, trying with zh-CN...");
            version = tryGetVersion(packageName, "zh", "cn");
            if (version != null) return version;

            // 第三次尝试
            System.out.println("Second attempt failed, trying last time...");
            return tryGetVersion(packageName, "en", "gb");

        } catch (Exception e) {
            System.err.println("Error processing " + packageName + ": " + e.getMessage());
            return null;
        }
    }

    private static String tryGetVersion(String packageName, String lang, String country) throws IOException {
        String url = String.format("%s?id=%s&hl=%s&gl=%s",
                PLAY_STORE_URL, packageName, lang, country);

        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                System.err.println("HTTP " + response.code() + " for " + packageName);
                return null;
            }

            ResponseBody body = response.body();
            if (body == null) {
                System.err.println("Empty response body");
                return null;
            }

            String html = body.string();
            return parseHtmlForVersion(html);
        }
    }

    private static String parseHtmlForVersion(String html) {
        // 方法1：从JSON数据提取
        String version = extractFromJson(html);
        if (version != null) return version;

        // 方法2：从meta标签提取
        version = extractFromMetaTags(html);
        if (version != null) return version;

        // 方法3：从可见文本提取
        version = extractFromVisibleText(html);
        if (version != null) return version;

        // 方法4：深度正则匹配
        version = extractWithDeepRegex(html);
        if (version != null) return version;

        System.err.println("All extraction methods failed");
        System.err.println("HTML snippet (first 500 chars):\n" +
                (html.length() > 500 ? html.substring(0, 500) : html));
        return null;
    }

    private static String extractFromJson(String html) {
        // 匹配多种可能的JSON格式
        Pattern[] patterns = {
                Pattern.compile("\"softwareVersion\"\\s*:\\s*\"([^\"]+)\""),
                Pattern.compile("\"version\"\\s*:\\s*\"([^\"]+)\""),
                Pattern.compile("\"currentVersion\"\\s*:\\s*\"([^\"]+)\"")
        };

        for (Pattern p : patterns) {
            Matcher m = p.matcher(html);
            if (m.find()) {
                System.out.println("Found version in JSON: " + m.group(1));
                return m.group(1);
            }
        }
        return null;
    }

    private static String extractFromMetaTags(String html) {
        try {
            Document doc = Jsoup.parse(html);

            // 尝试多种meta选择器
            String[] selectors = {
                    "meta[itemprop=softwareVersion]",
                    "meta[name=version]",
                    "meta[property=og:version]"
            };

            for (String selector : selectors) {
                org.jsoup.nodes.Element meta = doc.select(selector).first();
                if (meta != null) {
                    String version = meta.attr("content");
                    System.out.println("Found version in meta: " + version);
                    return version;
                }
            }
        } catch (Exception e) {
            System.err.println("Meta tag extraction error: " + e.getMessage());
        }
        return null;
    }

    private static String extractFromVisibleText(String html) {
        try {
            Document doc = Jsoup.parse(html);

            // 尝试多种可见文本模式
            String[] textPatterns = {
                    "Current Version",
                    "版本",
                    "Version"
            };

            for (String pattern : textPatterns) {
                org.jsoup.nodes.Element div = doc.select("div:contains(" + pattern + ")").first();
                if (div != null) {
                    String text = div.text().replaceAll(".*" + pattern + "\\s*", "").trim();
                    if (!text.isEmpty()) {
                        System.out.println("Found version in text: " + text);
                        return text;
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("Visible text extraction error: " + e.getMessage());
        }
        return null;
    }

    private static String extractWithDeepRegex(String html) {
        // 深度匹配各种可能的HTML结构
        Pattern[] patterns = {
                Pattern.compile("itemprop=\"version\"[^>]*>([^<]+)<"),
                Pattern.compile("Current Version\\D*([\\d.]+)"),
                Pattern.compile("版本\\D*([\\d.]+)"),
                Pattern.compile("Version\\s*</div>\\s*<div[^>]*>([^<]+)<"),
                Pattern.compile("data-version-name=\"([^\"]+)\"")
        };

        for (Pattern p : patterns) {
            Matcher m = p.matcher(html);
            if (m.find()) {
                System.out.println("Found version with deep regex: " + m.group(1));
                return m.group(1);
            }
        }
        return null;
    }

    public static void main(String[] args) {
        String[] testPackages = {
                "com.mobile.legends",
                "com.instagram.android",
                "com.whatsapp",
                "com.tencent.mm"
        };

        for (String pkg : testPackages) {
            long start = System.currentTimeMillis();
            String version = getAppVersion(pkg);
            long duration = System.currentTimeMillis() - start;

            System.out.printf("%-20s -> %-15s (%-4dms)%n%n",
                    pkg,
                    version != null ? version : "NOT FOUND",
                    duration);
        }
    }
}